package com.moyv.schoolbbs.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.tabs.TabLayout;
import com.moyv.schoolbbs.R;
import com.moyv.schoolbbs.bean.ReModel;
import com.moyv.schoolbbs.pojo.Comment;
import com.moyv.schoolbbs.pojo.Item;
import com.moyv.schoolbbs.service.MainService;
import com.moyv.schoolbbs.ui.activity.AddActivity;
import com.moyv.schoolbbs.ui.adapter.DataAdapter;
import com.moyv.schoolbbs.util.GlideCacheUtil;
import com.moyv.schoolbbs.util.UIHelper;
import com.moyv.schoolbbs.ui.listener.EndlessRecyclerOnScrollListener;
import com.moyv.schoolbbs.util.ToastUtils;

import java.util.ArrayList;
import java.util.List;

import static com.moyv.schoolbbs.base.Global.init;
import static com.moyv.schoolbbs.config.AccountConstant.LOGIN;
import static com.moyv.schoolbbs.config.URLConstant.IMAGE_URL;
import static com.moyv.schoolbbs.ui.adapter.DataAdapter.MAIN;

/**
 * @author moyv
 */
public class HomeFragment extends Fragment implements DataAdapter.Click {


    private static final int SUCCESS = 0;
    private static final int FALL = 404;
    private DataAdapter adapter;
    public static FloatingActionButton btnFlt;
    private SwipeRefreshLayout swiperefreshlayout;
    private Context mContext;
    private int start, end;
    private RecyclerView recyclerView;
    private List<ReModel.Main> lists;
    //    帖子总数
    private int count;

    private LinearLayout llComment;
    private EditText etComment1;
    private TabLayout tabLayout;
    private TextView tvSend;
    private int to_user_id;
    private String to_user_name;
    private int circle_id;
    private int commentPosition;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_main, container, false);
        start = 0;
        end = 5;
        mContext = root.getContext();

        recyclerView = root.findViewById(R.id.recycler_view);

        btnFlt = root.findViewById(R.id.btn_float);

        llComment = root.findViewById(R.id.ll_comment);

        etComment1 = root.findViewById(R.id.et_comment);

        tvSend = root.findViewById(R.id.tv_send_comment);

        tabLayout = root.findViewById(R.id.bottom_tab_layout);

        init(mContext);

        swiperefreshlayout = root.findViewById(R.id.swiperefreshlayout);

        swiperefreshlayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                                                    @Override
                                                    public void onRefresh() {
                                                        Log.d("zttjiangqq", "invoke onRefresh...");
                                                        start = 0;
                                                        end = 5;
                                                        new MainService(handler1).getPost(start, end);
                                                    }
                                                }

        );


        btnFlt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                判断是否登录
                if (LOGIN) {
                    Log.e("MainActivity", "onClick: 点击了跳转按钮");
                    Intent intent = new Intent(mContext, AddActivity.class);
                    startActivity(intent);
                } else {
                    Toast.makeText(mContext, "请先登录", Toast.LENGTH_SHORT).show();
                }
            }
        });
        //      设置滑动监听器
        recyclerView.addOnScrollListener(new EndlessRecyclerOnScrollListener() {
            @Override
            public void onLoadMore() {
                adapter.setLoadState(adapter.LOADING);
                if (end < count) {
                    if (end + 5 > count) {
                        start = end + 1;
                        end = count;
                    } else {
                        start = end + 1;
                        end = start + 4;
                    }

                    new MainService(handler2).getPost(start, end);
                } else {
                    // 显示加载到底的提示
                    adapter.setLoadState(adapter.LOADING_END);
                }


            }
        });
        new MainService(handler).getPost(start, end);
//        加载帖子数据
        UIHelper.showDialogForLoading(mContext, "初始化数据中");
        return root;
    }

    public static HomeFragment newInstance(String title) {
        Bundle arguments = new Bundle();
        arguments.putString("TITLE", title);
        HomeFragment fragment = new HomeFragment();
        fragment.setArguments(arguments);
        return fragment;
    }

    //    数据初始化
    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            UIHelper.closeDialog(mContext);
            List<Item> items = new ArrayList<>();
            switch (msg.what) {
                case SUCCESS:
                    //                    清除图片缓存
                    GlideCacheUtil glideCacheUtil;
                    glideCacheUtil = GlideCacheUtil.getInstance();
                    glideCacheUtil.clearImageAllCache(mContext);

                    Toast.makeText(mContext, "成功获取数据", Toast.LENGTH_SHORT).show();
                    ReModel reModel = (ReModel) msg.obj;
                    lists = reModel.getMain();
                    count = reModel.getCount();

                    for (ReModel.Main list : lists) {
                        Item item = new Item();
                        item.setMain(list);
                        System.out.println(list.getUserInfo().getIntroduction());
                        List<String> urls = new ArrayList<>();
                        for (int i = 0; i < list.getPost().getPostType(); i++) {
                            String url = IMAGE_URL + "/" + list.getPost().getPostId() + "/" + list.getPost().getPostId() + "_" + i + ".jpg";
                            urls.add(url);
                        }
                        item.setImagesUrls(urls);
                        items.add(item);
                    }

                    break;
                case FALL:
                    Toast.makeText(mContext, "连接服务器失败", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    System.out.println("返回信息出错");
            }
            // 显示帖子列表
            recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
            adapter = new DataAdapter(mContext, items, llComment, etComment1, tvSend);
            adapter.type = MAIN;
            Log.i("TAG", "handleMessage: " + items.size());
            recyclerView.setAdapter(adapter);
            return false;
        }
    });

    //    数据刷新
    Handler handler1 = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            swiperefreshlayout.setRefreshing(false);
            switch (msg.what) {
                case SUCCESS:
                    //                    清除图片缓存
                    GlideCacheUtil glideCacheUtil;
                    glideCacheUtil = GlideCacheUtil.getInstance();
                    glideCacheUtil.clearImageAllCache(mContext);


                    Toast.makeText(mContext, "成功获取数据", Toast.LENGTH_SHORT).show();
                    ReModel reModel = (ReModel) msg.obj;
                    lists = reModel.getMain();
                    count = reModel.getCount();
                    List<Item> items = new ArrayList<>();
                    for (ReModel.Main list : lists) {
                        Item item = new Item();
                        item.setMain(list);
                        List<String> urls = new ArrayList<>();
                        for (int i = 0; i < list.getPost().getPostType(); i++) {
                            String url = IMAGE_URL + "/" + list.getPost().getPostId() + "/" + list.getPost().getPostId() + "_" + i + ".jpg";
                            urls.add(url);
                        }
                        item.setImagesUrls(urls);
                        items.add(item);
                    }
                    adapter.refreshView(items);
                    break;
                case FALL:
                    Toast.makeText(getContext(), "刷新失败", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
            return false;
        }
    });

    //   数据添加
    Handler handler2 = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case SUCCESS:
                    ReModel reModel = (ReModel) msg.obj;
                    List<ReModel.Main> addLists = reModel.getMain();
                    List<Item> items = new ArrayList<>();
                    for (ReModel.Main list : addLists) {
                        Item item = new Item();
                        item.setMain(list);
                        List<String> urls = new ArrayList<>();
                        for (int i = 0; i < list.getPost().getPostType(); i++) {
                            String url = IMAGE_URL + "/" + list.getPost().getPostId() + "/" + list.getPost().getPostId() + "_" + i + ".jpg";
                            urls.add(url);
                        }
                        item.setImagesUrls(urls);
                        items.add(item);
                    }
                    adapter.setLoadState(adapter.LOADING_COMPLETE);
                    adapter.addDatas(items);
                    break;
                case FALL:
                    Toast.makeText(getContext(), "连接服务器失败", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
            return false;
        }
    });

    @Override
    public void Commend(int position, Comment bean) {
        circle_id = bean.getPostId();
        commentPosition = position;
        to_user_name = bean.getCmtName();
        to_user_id = bean.getCommentAccount();
    }
}
